<template>
  <div id="samstoSpecboxList">
    <div class="bodyContent">
      <div class="text-bold text-shadow text-18">
        <span class="margin-right">当前选中:</span><span class="text-blue">{{ dataForm.stoPidName }}</span>/<span
          class="text-green">{{ dataForm.stoName }}</span>/<span class="text-orange">{{ dataForm.fridge }}</span>/<span
          class="text-olive">{{ dataForm.layer }}</span>/<span class="text-pink">{{ dataForm.orderNumber }}</span>
      </div>
      <div class='area'>
<!--        <vxe-toolbar class-name="bg-grey light">
          <template #buttons>
            <vxe-button type="text" class="button-blue" content="选择标本盒" @click="changeBoxOrder"></vxe-button>
            <vxe-button type="text" class="button-blue" content="确认借出" @click="askBoxOrder"></vxe-button>
          </template>
        </vxe-toolbar>-->
        <div class="tableBox">
          <div class="sample-box">
            <div class="rack">
              <div v-for="row in boxData.lData" :key="'row-' + row" class="rack-row">
                <div v-for="col in boxData.wData" :key="'col-' + col" class="rack-cell"
                  :class="[getCellClass(row, col), getIsActived(row, col) ? 'selected' : '']"
                  @click="selectCell(row, col)">
                  <span class="cell-label">{{ row }}{{ col }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- <el-drawer v-model="drawer" title="架层信息">
        <SamstoSpecboxForm ref="samstoSpecboxFormRef" :currentRow="curSelectRow" @findList="findList" />
      </el-drawer> -->
    </div>
    <vxe-modal :title="`留样盒信息`" width="90vw" height="88vh" v-model="dialogFormVisible" draggable show-footer mask-closable
      :mask="false">
      <template #title>
        <span class="margin-right">请选择留样盒</span>
      </template>
      <template #default>
        <StoragedisplayV1 :isBreadcrumb="false" @changeBox="changeBox" />
      </template>
      <template #footer>
        <div class="flex justify-end">
          <el-button type="primary" v-loading="showLoading" @click="dialogFormVisible = false">确定</el-button>
          <el-button @click="dialogFormVisible = false"> 取消</el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, PropType } from 'vue';
import type { VxeTableInstance } from 'vxe-table';
import { AppStore } from '@/stores/store';
import SamstoSpecboxForm from "./SamstoSpecboxForm.vue";
import { IsEmpty, getAssetsFile, formatDateTime } from '@/utils/common';
import { samstoSpecboxFindInfoByCode } from '@/views/lab_sys/samsto_set/apis/samsto_api';
import { isEmpty } from 'xe-utils';
import { forEach } from 'lodash';
import StoragedisplayV1 from '@/views/lab_sys/samsto_set/StoragedisplayV1.vue';
import { VxeMessage, VxeNotifyType } from "@/utils/CommonMessage";
let store = AppStore();

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let dialogFormVisible = ref(false);
// 左侧表格:
let showLoading = ref(false); //刷新+表格加载
const form = reactive({ keyvalue: '' }); //根据关键字查询
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableData = reactive<Map<String, SpecboxOrder>[]>([]); //表格数据
const selectStartItem = ref({}); //表格数据
const tableHard = ref([
  { title: "#", field: "#" },
  { title: "A", field: "A" },
  { title: "B", field: "B" },
  { title: "C", field: "C" },
  { title: "D", field: "D" },
  { title: "E", field: "E" },
  { title: "F", field: "F" },
  { title: "G", field: "G" },
  { title: "G", field: "G" },
  { title: "H", field: "I" },
]); //表头
const orderNumberArr = reactive([]);
const specboxOrderList = reactive([]);
const curSelectRow = ref({});
const info = ref({});
let tableHeight = ref(window.innerHeight - 200);
const drawer = ref(false)
// 右侧表单:
const samstoSpecboxFormRef = ref<InstanceType<typeof SamstoSpecboxForm>>(); //基本信息表单标记ref
const selectDomId = ref("");


let dataForm = reactive({
  stoPidName: '',
  stoName: '',
  fridge: '',
  layer: '',
  orderNumber: '',
});

interface SpecboxOrder {
  id: String /*主键*/;
  specimenId: String;/*标本ID */
  specboxId: String;/*标本盒表 */
  orderNumber: String;/*库位号 */
  empty: Number;/*存储状态 0为空，1为放置 */
  status: Number;/*状态 */
  deptName: String;/* */
  orderRow: String;/*行号 */
  orderColumn: String;/*列名称 */
}
// 库存表
interface SamstoSampleStorage {
  id: String /*主键*/;
  specimenId: String;/*标本ID */
  specimenType: String;/*标本类型 */
  workGroup: String;/*工作组 */
  operator: String;/*操作人 */
  fridgeId: String;/*所在冰箱 */
  layerId: String;/*所在层 */
  specboxId: String;/*标本盒表 */
  orderNumber: String;/*库位号 */
  location: String;/*仓库位置 */
  inspectionTime: String;/*检验时间 */
  inTime: String;/*入库时间 */
  expirationTime: String;/*存储到期时间 */
  status: Number;/*状态 */
  deptName: String;/*所属科室 */
}
// 绑定库存数据
let sSlist = reactive<SamstoSampleStorage[]>([]);
let sBOlist = reactive<SpecboxOrder[]>([]);
let formData = reactive({});

let boxData = reactive({
  id: '',
  lData: [],
  wData: [],
  specboxOrders: []
});



defineExpose({
  initPage, selectSpecboxOrder
});
// 父组件传值
let props = defineProps({
  //  infoDicts: { type: Array as PropType<any>, required: true },
  curSelectRow: { type: Object as PropType<any>, required: true }
}) as any;

async function initPage(selsectRow: any) {
  //findList();
}
interface Cell {
  row: String;
  col: String;
  status: CellStatus;
}
// 初始状态
const cells = ref<Cell[]>([]);
type CellStatus = 'empty' | 'waitOccupied' | 'occupied' | 'unoccupied' | 'selected' | 'borrowed';

// 方法定义区 =============
onMounted(() => {

});

/**选择样本盒 */
function changeBoxOrder() {
  dialogFormVisible.value = true;
}

//设置成已占用
// function setOccupied(specboxOrderList) {
//   for (const item of specboxOrderList) {
//     const cell = cells.value.find(cell => cell.row === item.row && `${cell.col}` === `${item.col}`);
//     cell.status = 'occupied';
//   }
// }

let storageList = reactive([]);//冰箱列表
//左侧列表点击事件
function selectSpecboxOrder(selsectRows: any) {
  Object.assign(formData, selsectRows);
  dataForm.stoPidName = selsectRows.storagePname;
  dataForm.stoName = selsectRows.storageName;
  dataForm.fridge = selsectRows.fridgeCode;
  dataForm.layer = selsectRows.layerCode;
  dataForm.orderNumber = selsectRows.orderNumber;

  storageList.length = 0;
  const url = '/api/samsto/specboxOrderReq/getSpecboxOrderReqList';
  proxy.$http
    .get(url, { params: { id: selsectRows.specboxId } })
    .then((res: any) => {
      if (res.status.code === 1) {
        storageList = res.data;

        changeBox(storageList, selsectRows);
      }
    })
    .catch((err) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 获取单元格状态
const getCellClass = (row: string, col: string) => {
  const cell = cells.value.find(cell => `${cell.row}` === `${row}` && `${cell.col}` === `${col}`);
  return cell ? cell.status : 'empty';
};
const getIsActived = (row: string, col: string) => {
  const cell = cells.value.find(cell => `${cell.row}` === `${row}` && `${cell.col}` === `${col}`);
  return cell && cell.isactived ? true : false;
};
// 点击选择状态
const selectCell = (row: String, col: String) => {
  cells.value.forEach((m) => {
    m.isactived = false;
  });
  const cell = cells.value.find(cell => cell.row === row && `${cell.col}` === `${col}`);
/*  if (cell) {
    switch (cell.status) {
      case 'occupied':
        cell.status = 'selected';
        cell.isactived = true;
        break;
      case 'selected':
        cell.status = 'occupied';
        break;
      // case 'selected':
      //   cell.status = 'occupied';
      //   break;
    }
  }*/
};

//获取选中的试剂盒
function changeBox(val: any, selsectRows: any) {
  console.log('val...', val);
  console.log('changeBox.selsectRows', selsectRows);
  boxData.lData.length = 0;
  boxData.wData.length = 0;
  boxData.specboxOrders.length = 0;
  cells.value.length = 0;
  boxData.lData.push(...val.orderColumns);
  boxData.wData.push(...val.orderRows);
  boxData.specboxOrders.push(...val.specboxOrders);
  boxData.id = val.id;
  for (let row = 0; row < boxData.lData.length; row++) {
    for (let col = 0; col < boxData.wData.length; col++) {
      //添加集合遍历
      const data = {
        row: boxData.lData[row],
        col: `${boxData.wData[col]}`,
        status: 'empty', // 初始状态为空位
        isactived: false
      }
      cells.value.push(data);
    }
  }
  console.log('boxData.specboxOrders', boxData.specboxOrders);

  //动态塞入样本盒id和仓位id
  for (const val of cells.value) {
    for (const val1 of boxData.specboxOrders) {
      if (val.row + val.col == val1.orderNumber && val1.empty == 1) {
        val.status = 'occupied';
        if (selsectRows.orderNumber == val1.orderNumber) {
          console.log('val2', val1);
          val.status = 'selected';
        }
      }

      // if (val.row + val.col == val1.orderNumber && selsectRows.orderNumber == val2.orderNumber && val1.empty == 1) {
      //   val.status = 'occupied';
      // }

    }

  }

  // for (const val2 of boxData.specboxOrders) {
  //   if (selsectRows.orderNumber == val2.orderNumber) {
  //     console.log('val2', val2);
  //     val2.status = 'selected';
  //   }
  // }


  //dialogFormVisible.value = true;
}
</script>
<style lang="scss" scoped>
#samstoSpecboxList {
  width: 100%;
  height:calc(100% - 40px);

  .bodyContent {
    background-color: #fff;
    height: calc(100% - 20px);

    .hand-cursor {
      cursor: pointer;
      /* 鼠标指针在元素上时显示为手指形状 */
    }

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .select-active {
        border-color: chocolate;
        border-style: dotted;
      }

      .tableBox {
        width: 100%;
        height: calc(100% - 40px);
      }

      .el-tabs {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);

          .el-tab-pane {
            height: 100%;
          }

          #pane-0 {
            padding: 15px;
            height: calc(100% - 30px);
          }
        }
      }
    }

    .bankItemContent {
      min-height: 600px;
      border-radius: 10px;
    }

    .disabled {
      pointer-events: none;
      opacity: 0.5;
    }
  }
}

.sample-box {
  width: 100%;
  height: auto;
  // padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.rack {
  width: 100%;
  display: flex;
  flex-direction: column;
  border: 2px solid #eee;
  border-radius: 5px;
}

.rack-row {
  width:100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  word-break: break-all;
}

.rack-cell {
  width: 33px;
  min-width: 33px;
  height: 33px;
  margin: 3px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.rack-cell.empty {
  background-color: #e0e0e0;
  /* 空位 */
}

.rack-cell.unoccupied {
  background-color: #32cd32;
  /* 未占用（绿色） */
}

.rack-cell.selected {
  background-color: #1e90ff;
  /* 选中（蓝色） */
}

.rack-cell.waitOccupied {
  background-color: #ff6347;
  /* 待占用（粉色） */

}

.rack-cell.occupied {
  background-color: #f80707;
  /* 已占用（红色） */
}


.rack-cell.borrowed {
  background-color: #ffeb3b;
  /* 借出（黄色） */
}
</style>

